<template>
  <el-container class="setting_role-setting">
    <el-main>
      <el-card shadow="never" class="selectCard searchColumn">
        <el-form label-position="right" label-width="6rem">
          <el-row :gutter="40">
            <el-col :span="8">
              <el-form-item label="角色名称：">
                <el-input v-model="params.name" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <SearchButton :default-params="params" @refreshParams="refreshParams" @getList="getList1" />
            </el-col>
          </el-row>
        </el-form>
      </el-card>
      <el-card shadow="never" class="tableCard">
        <vxe-toolbar :refresh="{query: getList1}">
          <template v-slot:buttons>
            <el-button type="primary" icon="el-icon-plus" @click="openDialog('')">新增</el-button>
          </template>
        </vxe-toolbar>
        <vxe-table
          ref="xTable"
          border
          resizable
          highlight-hover-row
          :auto-resize="true"
          :data="tableData"
          width
          max-height="500"
          :print-config="{}"
        >
          <vxe-table-column type="seq" width="50" title=" " />
          <vxe-table-column field="name" width="120" title="角色名称" />
          <vxe-table-column field="remark" min-width="200" title="角色描述">
            <template slot-scope="scope">
              <p class="overflow2" :title="scope.row.remark">{{ scope.row.remark }}</p>
            </template>
          </vxe-table-column>
          <vxe-table-column field="count" width="80" align="right" title="账号数量" />
          <vxe-table-column title="状态" width="80" align="center" slots="default">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.publishStatus" :inactive-value="0" :active-value="1" active-text inactive-text @change="changeState(scope)" />
            </template>
          </vxe-table-column>
          <vxe-table-column title="操作" fixed="right" align="center" width="160" slots="default">
            <template slot-scope="scope">
              <el-button type="text" size="mini" @click="openDialog(scope.row.id)">编辑</el-button>
              <el-button type="text" size="mini" @click="delRoleById(scope.row.id)">删除</el-button>
              <el-button type="text" size="mini" @click="setUser(scope.row.id)">用户关联</el-button>
            </template>
          </vxe-table-column>
        </vxe-table>
        <vxe-pager
          :current-page.sync="params.pageNum"
          :page-size.sync="params.pageSize"
          :total="total"
          :layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'FullJump', 'Total']"
          @page-change="getList()"
        />
      </el-card>
    </el-main>
    <el-dialog v-if="dialogVisible" :close-on-click-modal="false" :visible.sync="dialogVisible" title="用户分配" width="50%">
      <div style="text-align:center">
        <vxe-table
          ref="treeTable"
          :auto-resize="true"
          resizable
          row-id="id"
          :checkbox-config="{checkRowKeys: defaultSelecteRows}"
          tree-config
          border
          highlight-hover-row
          highlight-current-row
          height="400"
          :data="userList"
        >
          <vxe-table-column type="checkbox" field="checked" width="40" />
          <vxe-table-column field="name" min-width="100" title="姓名" />
          <vxe-table-column field="userCode" min-width="150" title="账号" />
          <vxe-table-column field="mobile" min-width="150" title="手机" />
        </vxe-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setUserRole()">保存</el-button>
      </span>
    </el-dialog>
    <el-dialog v-if="dialogFormVisible" :title="title + '角色'" :close-on-click-modal="false" :visible.sync="dialogFormVisible">
      <el-form ref="addForm" :model="addParams" label-position="right" :rules="addRules" label-width="6rem">
        <el-row>
          <el-col :span="12">
            <el-form-item label="角色名称：" prop="name">
              <el-input v-model="addParams.name" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序：" class="flex-just">
              <el-input v-model="addParams.sort1" @focus="sortF" @blur="sortC" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="角色描述：">
              <el-input v-model="addParams.remark" type="textarea" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="clickSure">确 定</el-button>
      </div>
    </el-dialog>
  </el-container>
</template>

<script>
import SearchButton from '@/components/SearchButton'
import { getRoleList, addRole, delRole, searchRole, editRole, changeRoleStatus, getCpUserList, getUserInfoByRoleId, userModifyByRoleId } from '@/api/cpPermission'
import { filterNumber, removeNumber } from '@/utils/filter'

export default {
  components: {
    SearchButton
  },
  data() {
    return {
      csParams: {
        publishStatus: 1,
        pageNum: 1,
        pageSize: 20
      },
      csTotal: 0,
      addParams: {},
      addRules: {
        // code: [{ required: true, message: '请输入角色编码', trigger: 'blur' }],
        name: [{ required: true, message: '请输入姓名', trigger: 'blur' }]
        // sort: [{ required: true, message: '请输入排序', trigger: 'blur' }]
      },
      dialogFormVisible: false,
      chooseUser: [],
      userIds: [],
      userIdsNew: [],
      userList: [],
      title: '',
      dialogVisible: false,
      params: {
        pageNum: 1,
        pageSize: 20
      },
      tableData: [],
      total: 0,
      nowRoleId: '',
      defaultSelecteRows: []
    }
  },
  mounted() {
    this.getList()
  },
  methods: {
    // 排序
    sortF() {
      this.addParams.sort1 = removeNumber(this.addParams.sort1)
    },
    sortC(val) {
      this.addParams.sort = val.currentTarget.value
      this.$set(this.addParams, 'sort1', filterNumber(val.currentTarget.value))
    },
    setUserRole() {
      this.userIds = []
      this.chooseUser = this.$refs.treeTable.getCheckboxRecords()
      if (this.chooseUser.length === 0) {
        this.$message.error('请选择用户')
        return false
      }
      this.chooseUser.forEach((item, index) => {
        this.userIds[index] = item.id
      })
      var paramsVal = {
        userIds: this.userIds,
        roleId: this.nowRoleId
      }
      userModifyByRoleId(paramsVal).then(res => {
        this.dialogVisible = false
      })
    },
    openDialog(id) {
      this.title = id === '' ? '新增' : '编辑'
      this.addParams = { image: '' }
      if (id !== '') {
        searchRole({ id }).then(res => {
          this.addParams = res
          this.$set(this.addParams, 'sort1', filterNumber(this.addParams.sort))
          this.dialogFormVisible = true
        })
      } else {
        this.dialogFormVisible = true
      }
    },
    clickSure() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          if (this.title === '新增') {
            addRole(this.addParams).then(res => {
              this.$message.success('新增成功！')
              this.getList()
              this.dialogFormVisible = false
            })
          } else {
            editRole(this.addParams).then(res => {
              this.$message.success('编辑成功！')
              this.getList()
              this.dialogFormVisible = false
            })
          }
        }
      })
    },
    refreshParams(params) {
      this.params = params
      this.getList()
    },
    getList1() {
      this.params.pageNum = 1
      this.getList()
    },
    setUser(id) {
      this.dialogVisible = true
      this.nowRoleId = id
      getCpUserList(this.csParams).then(res => {
        this.userList = res.records
        this.csTotal = res.total
        getUserInfoByRoleId(id).then(res1 => {
          res1.forEach((item, index) => {
            this.userList.forEach((it, idx) => {
              if (item === it.id) {
                this.$refs.treeTable.setCheckboxRow(this.userList[idx], true)
              }
            })
          })
        })
      })
    },
    getList() {
      getRoleList(this.params).then(res => {
        this.tableData = res.records
        this.total = res.total
      })
    },
    changeState(scope) {
      this.tableData[scope.seq - 1].publishStatus = scope.row.publishStatus === 1 ? 0 : 1
      changeRoleStatus({ id: scope.row.id, status: scope.row.publishStatus === 1 ? 0 : 1 }).then(res => {
        this.tableData[scope.seq - 1].publishStatus = scope.row.publishStatus === 1 ? 0 : 1
        this.$message.success(scope.row.publishStatus === 0 ? '禁用成功' : '启用成功')
      })
    },
    delRoleById(id) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delRole({
          id: id
        }).then(res => {
          this.$message.success('删除成功')
          this.getList()
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    }
  }
}
</script>

<style lang="scss">
.customer_role {}
</style>
